﻿CREATE PROCEDURE [acms].[Email_Put]
	@Id int, 
	@UserId int,
	@EmailAddress varchar(255),
	@Name varchar(100),	
	@FilePath varchar(200),
	@To varchar(200),
	@Cc varchar(200),
	@Bcc varchar(200),
	@From varchar(200),
	@ReplyTo varchar(200),
	@Subject varchar(200),
	@Body varchar(2000),
	@Html bit,
	@Created Datetime,
	@Sent DateTime,
	@Failed bit,
	@ConcurencyId rowversion,
	@IdOut int output,
	@ConcurencyIdOut rowversion output
	
AS
	if @Id is null or @Id = 0 begin
		insert into Email
			(UserId, [Name], [EmailAddress], FilePath, [To], CC, Bcc, [From], ReplyTo, Subject, Body, Html, Sent, Failed, Created)
		values
			(@UserId, @Name, @EmailAddress, @FilePath, @To, @CC, @Bcc, @From, @ReplyTo, @Subject, @Body, @Html, @Sent, @Failed, @Created)
		set @IdOut = @@Identity
	end
	else if exists (select null from Email with (nolock) Where Id = @Id and ConcurencyId = @ConcurencyId) begin
		Update Email
		set
			UserId = @UserId, 
			[Name] = @Name,
			[EmailAddress] = @EmailAddress,
			FilePath = @FilePath, 
			[To] = @To, 
			CC = @CC, 
			Bcc = @Bcc, 
			[From] = @From, 
			ReplyTo = @ReplyTo, 
			Subject = @Subject, 
			Body = @Body, 
			Html = @Html, 
			Sent = @Sent,
			Failed = @Failed
		Where Id = @Id and ConcurencyId = @ConcurencyId
		
		set @IdOut = @Id
	end
	else if exists(select null from Email with (nolock) Where Id = @Id)
		return -100
	else
		return -200
	
	select @ConcurencyIdOut = ConcurencyId from Email with (nolock) where Id = @IdOut
		
RETURN 0;